<template>
	<view class="content bgGray">
		<view class="bgWhite flex-r jsb p16" style="border-bottom: 1rpx solid #eee">
			<view>商品名称</view>
			<view class="gray f1">
				<input type="text" class="fs13 pl16" placeholder="请输入商品名称" v-model="form.tCommodityname" />
			</view>
		</view>
		<view class="bgWhite ver-c p16">
			<view class="mb16">商品图片</view>
			<view class="flex-r upload-img wrap">
				<view v-for="(image, imgIndex) in fileList" :key="imgIndex">
					<view class="uni-uploader__file">
						<image
							class="uni-uploader__img"
							:src="image.ip + image.url"
							:data-src="image.url"
							@click="preview(image.ip + image.url)"
							@longtap="onDeleteClick(imgIndex, index)"
						></image>
					</view>
				</view>
				<image src="/static/img/add@2x.png" class="img" @tap="onGetImgClick()" v-if="isAdd || isEdit"></image>
			</view>
		</view>
		<!-- <view class="bgWhite flex-r jsb p16" style="border-bottom: 1rpx solid #eee">
			<view>商品简介</view>
			<view class="gray">
				<input type="text" class="textRight" v-model="form.tCommoditybrief" />
			</view>
		</view> -->
		<view class="bgWhite mt6 p16" style="border-bottom: 1rpx solid #eee">
			<view>商品详情</view>
			<view class="gray">
				<textarea
					type="text"
					class="textarea"
					placeholder="请输入商品详情.."
					v-model="form.tCommodityintroduce"
				/>
			</view>
		</view>

		<view class="savebtn textCenter white" @tap="save()" v-if="isAdd">新增</view>
		<view class="savebtn textCenter white" @tap="attr()" v-if="isEdit">修改</view>
	</view>
</template>

<script>
import Utils from '@/utils/utils.js'
import { goodsAdd, goodsEdit } from '@/api/mine.js'
import { IP, ImgIP, throttle } from '@/utils/comm.js'
export default {
	data() {
		return {
			fileList: [], //上传图片
			token: '',
			isAdd: true,
			isEdit: false,
			form: {
				tMerchantid: '', //商户id
				tCommodityname: '', //商品名称
				tCommodityimg: '', //图片
				tCommoditybrief: '' //商品简介
			}
		}
	},
	onLoad(option) {
		let data = option.data
		let type = option.type
		console.log(option)
		this.form.tMerchantid = option.tMerchantid
		if (data) {
			data = JSON.parse(decodeURIComponent(data))
			console.log(data)
			this.form = data
			if (data.tCommodityimg) {
				this.fileList = data.tCommodityimg.split(',').map((item) => {
					return {
						url: item,
						ip: ImgIP
					}
				})
			}
		}
		if (type == 'detail') {
			this.isEdit = false
			this.isAdd = false
			uni.setNavigationBarTitle({
				title: '商品详情'
			})
		} else if (type == 'edit') {
			uni.setNavigationBarTitle({
				title: '修改商品'
			})
			this.isAdd = false
			this.isEdit = true
		}
	},

	onShow() {
		let token = Utils.getToken()
		console.log(token)
		this.token = token
	},
	methods: {
		save: throttle(function (e) {
			this.form.tCommodityimg = this.fileList.length > 0 ? this.fileList.map((item) => item.url).join(',') : ''

			console.log(this.form)
			goodsAdd(this.form).then(
				(res) => {
					console.log(res)
					if (res.code == 200) {
						uni.$emit('updateGoodList', true)
						uni.navigateBack({
							delta: 1,
							success: function () {
								setTimeout(() => {
									Utils.toast(res.msg)
								}, 300)
							}
						})
					} else {
						Utils.toast(res.msg)
					}
				},
				(err) => {
					console.log(err)
				}
			)
		}),
		//修改
		attr: throttle(function (e) {
			this.form.tCommodityimg = this.fileList.length > 0 ? this.fileList.map((item) => item.url).join(',') : ''
			goodsEdit(this.form).then(
				(res) => {
					console.log(res)
					if (res.code == 200) {
						uni.$emit('updateGoodList', true)
						uni.navigateBack({
							delta: 1,
							success: function () {
								setTimeout(() => {
									Utils.toast(res.msg)
								}, 300)
							}
						})
					} else {
						Utils.toast(res.msg)
					}
				},
				(err) => {
					console.log(err)
				}
			)
		}),
		onGetImgClick() {
			const that = this
			uni.chooseImage({
				count: 9, // 最多可以选择的图片张数，默认9
				sizeType: ['original', 'compressed'], //original 原图，compressed 压缩图，默认二者都有
				sourceType: ['album', 'camera'], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
				success: function (res) {
					if (!that.fileList) {
						that.fileList = []
					}
					const len = that.fileList.length
					if (len >= 9) {
						uni.showToast({
							title: '图片最多上传9张'
						})
					} else {
						for (let i = 0; i < 9 - len; i++) {
							if (res.tempFilePaths[i]) {
								that.uploadFilePromise(res.tempFilePaths[i])
							}
						}
					}
				}
			})
		},
		//上传图片
		uploadFilePromise(url) {
			//var tempFile = [
			//{
			//name: 'file',
			//uri: url
			//}
			//]
			//console.log('???-->', url)
			return new Promise((resolve, reject) => {
				//console.log('1111')
				let a = uni.uploadFile({
					url: IP + 'common/upload',
					filePath: url, //小程序
					//files: tempFile,	//app
					header: {
						Authorization: 'Bearer ' + this.token
					},
					name: 'file',
					success: (res) => {
						//console.log('上传成功', res)
						let imgObj = res.data
						let obj = JSON.parse(imgObj)
						if (obj.url) {
							if (!this.fileList) {
								this.fileList = []
							}
							this.fileList.push({ ip: ImgIP, url: obj.fileName })
							console.log(this.fileList)
							this.fileList = Object.assign([], this.fileList)
						} else {
							uni.$u.toast(obj.msg)
						}

						//隐藏上传中
						setTimeout(() => {
							resolve(res.data.data)
						}, 1000)
					},
					fail: (err) => {
						console.log(err)
					}
				})
			})
		},
		// 预览图片
		preview(img) {
			console.log('预览')
			// 新建一个存放预览图片的空数组
			var imgArr = []
			imgArr.push(img)
			uni.previewImage({
				urls: imgArr,
				current: imgArr[0],
				longPressActions: {}
			})
		},
		// 长按删除图片
		onDeleteClick(imgIndex, index) {
			// this.imageList.splice(index, 1)
			uni.showModal({
				title: '删除图片',
				content: '确定删除图片?',
				success: (res) => {
					if (res.confirm) {
						// 删除图片 将数据置空
						this.fileList.splice(imgIndex, 1)
						console.log('??', this.fileList)
					} else if (res.cancel) {
						console.log('用户点击取消')
					}
					this.fileList = Object.assign([], this.fileList)
				}
			})
		}
	}
}
</script>

<style lang="stylus" scoped>
.content
	height 100%
.mt6
	margin-top 12rpx
.textarea
	border-radius: 20rpx
	background: #f5f5f5
	padding 20rpx
	height 260rpx
	width 100%
	box-sizing border-box
	margin-top 30rpx
.img
	padding 60rpx 50rpx
	background #f5f5f5
	border-radius 14rpx
	width 50rpx
	height 40rpx
.uni-uploader__img
	width 150rpx
	height 150rpx
	border-radius(14rpx)
	margin 5rpx
.savebtn
	margin 60rpx 32rpx 0
	border-radius 50rpx
	background #c40414
	line-height 90rpx
</style>
